package com.sy.config;

import com.sy.bean.HttpOperation;
import com.sy.constant.AppConstant;
import com.sy.filter.CommonExceptionFilter;
import com.sy.filter.JwtAuthenticationTokenFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true, prePostEnabled = true)
@Import(BCryptPasswordEncoder.class)
@Slf4j
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CacheDetailService cacheDetailService;

    @Autowired
    private HttpOperation httpOperation;



    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(cacheDetailService).passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(WebSecurity web){
        web.ignoring().mvcMatchers("/v1.0/login","/v1.0/validateCode",
                "/swagger-ui.html",
                "/swagger-resources/**",
                "/images/**",
                "/webjars/**",
                "/v2/api-docs",
                "/configuration/ui",
                "/configuration/security");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        //前后端分离项目中不需要这个登录表单
        //        http.formLogin()
//                .successHandler((req, res, authentication) -> {
//                    //200
//                    httpOperation.writeJson(HttpStatus.OK.value(), authentication.getPrincipal());
//                })
//                .failureHandler((req, res, exception) -> {
//                    //401
//                    httpOperation.writeJson(HttpStatus.UNAUTHORIZED.value(), "用户名或密码有误");
//                })
//                .permitAll();
        http.authorizeRequests()
                .mvcMatchers("/**").hasAnyRole(AppConstant.ROLE_SURPERADMIN_NAME.replace("ROLE_", ""), AppConstant.ROLE_GENERALADMIN_NAME.replace("ROLE_", ""),AppConstant.ROLE_EDITADMIN_NAME.replace("ROLE_", ""));
        http.exceptionHandling().accessDeniedHandler((req, res, accessDeniedException) -> {
            //403
            throw new AccessDeniedException("您没有执行该操作的权限,如要获取权限请联系管理员！");
        });

        //添加全局异常处理过滤器
        http
                .addFilterBefore(new CommonExceptionFilter(), ChannelProcessingFilter.class);

        // 添加JWT过滤器
        // 用于在每次需要鉴权的请求时判断当前请求携带的JWT是否为空、格式是否合法、是否过期……
        //以及该JWT中的用户信息和数据库中的是否保持一致
        http
                .addFilterBefore(new JwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
